<template>
  <div class="chat-container">
    <!-- 聊天内容区域 -->
    <el-card class="chat-content">
      <div 
        v-for="(msg, index) in messageList" 
        :key="index" 
        class="message-item"
        :class="{ 'self': msg.isSelf }"
      >
        <div class="message-content" :style="{ background: msg.isSelf ? '#409EFF' : '#ECECEC', color: msg.isSelf ? '#fff' : '#000' }">
          {{ msg.content }}
        </div>
      </div>
    </el-card>
    
    <!-- 输入区域 -->
    <el-card class="chat-input-area">
      <el-input 
        v-model="inputValue" 
        placeholder="请输入您的问题" 
        class="input-box"
        @keyup.enter.native="sendMessage"
      ></el-input>
      <el-button 
        type="primary" 
        @click="sendMessage"
        :disabled="connectionStatus !== 'connected'"
      >
        {{ connectionStatus === 'connected' ? '发送' : '连接中...' }}
      </el-button>
      <el-button 
        type="danger" 
        @click="cancelRequest"
        :disabled="!isStreaming"
      >
        取消
      </el-button>
    </el-card>
    
    <!-- 状态提示 -->
    <el-alert
      v-if="connectionStatus === 'connecting'"
      title="正在连接AI助手..."
      type="info"
      :closable="false"
    ></el-alert>
    
    <el-alert
      v-if="connectionStatus === 'error'"
      :title="errorMessage"
      type="error"
      @close="reconnect"
    ></el-alert>
    
    <!-- 调试信息 -->
    <el-card v-if="debugInfo" class="debug-info">
      <div class="debug-title">调试信息</div>
      <pre>{{ debugInfo }}</pre>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ChatComponent',
  data() {
    return {
      inputValue: '',
      messageList: [],
      model: 'generalv3.5', // 默认使用Max版本
      url: '/api/chat', // 修改为代理路径
      connectionStatus: 'connected',
      errorMessage: '',
      debugInfo: null,
      controller: null,
      isStreaming: false,
      retryCount: 0,
      maxRetries: 3
    }
  },
  mounted() {
    this.messageList.push({ 
      content: "你好！我是AI智慧助手，有什么可以帮助你的吗？", 
      isSelf: false 
    })
  },
  methods: {
    // 发送消息
    async sendMessage() {
      if (!this.inputValue.trim()) return
      
      if (this.isStreaming) {
        this.$message.warning('请等待当前回复完成')
        return
      }
      
      this.messageList.push({ content: this.inputValue, isSelf: true })
      this.retryCount = 0
      
      await this._sendRequest()
      this.inputValue = ''
    },
    
    // 实际发送请求（支持重试）
    async _sendRequest() {
      try {
        this.isStreaming = true
        this.connectionStatus = 'connecting'
        
        this.controller = new AbortController()
        const signal = this.controller.signal
        
        const headers = {
          'Content-Type': 'application/json',
          // 移除Authorization头，由代理服务器处理
        }
        
        const data = {
          model: this.model,
          messages: this.messageList.map(msg => ({
            role: msg.isSelf ? 'user' : 'assistant',
            content: msg.content
          })),
          stream: true
        }
        
        this.debugInfo = {
          request: {
            url: this.url,
            headers,
            data
          },
          timestamp: new Date().getTime(),
          retry: this.retryCount
        }
        
        // 尝试解析域名，检查连接性
        await this._checkConnection()
        
        const response = await fetch(this.url, {
          method: 'POST',
          headers,
          body: JSON.stringify(data),
          signal
        })
        
        if (!response.ok) {
          throw new Error(`HTTP错误 ${response.status}: ${response.statusText}`)
        }
        
        this.messageList.push({ content: '', isSelf: false })
        const reader = response.body.getReader()
        const decoder = new TextDecoder('utf-8')
        let aiResponse = ''
        
        while (true) {
          const { done, value } = await reader.read()
          
          if (done) {
            this.connectionStatus = 'connected'
            this.isStreaming = false
            break
          }
          
          const chunk = decoder.decode(value)
          const lines = chunk.split('\n').filter(line => line.trim() !== '')
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const dataStr = line.substring(6)
              
              if (dataStr === '[DONE]') {
                continue
              }
              
              try {
                const data = JSON.parse(dataStr)
                if (data.choices && data.choices[0].delta && data.choices[0].delta.content) {
                  aiResponse += data.choices[0].delta.content
                  this.messageList[this.messageList.length - 1].content = aiResponse
                }
              } catch (error) {
                console.error('解析响应失败:', error)
                this.debugInfo.error = `解析响应失败: ${error.message}`
              }
            }
          }
        }
      } catch (error) {
        this.debugInfo = {
          ...this.debugInfo,
          error: error.message,
          stack: error.stack
        }
        
        if (error.name !== 'AbortError') {
          if (this.retryCount < this.maxRetries) {
            // 指数退避重试
            this.retryCount++
            const delay = Math.pow(2, this.retryCount) * 500
            this.$message.warning(`请求失败，${delay/1000}秒后尝试重试 (${this.retryCount}/${this.maxRetries})`)
            
            setTimeout(async () => {
              await this._sendRequest()
            }, delay)
          } else {
            this.errorMessage = `发送请求失败: ${error.message}`
            this.connectionStatus = 'error'
            this.$message.error(this.errorMessage)
          }
        }
      } finally {
        if (this.controller && !this.isStreaming) {
          this.controller = null
        }
      }
    },
    
    // 检查连接性（尝试解析域名）
    async _checkConnection() {
      try {
        // 修改为检查本地代理服务器
        const testResponse = await fetch('/api/chat', {
          method: 'HEAD',
          mode: 'no-cors',
          cache: 'no-cache',
          timeout: 5000
        })
        
        if (!testResponse.ok) {
          throw new Error(`无法连接到代理服务器 (状态码: ${testResponse.status})`)
        }
      } catch (error) {
        console.error('连接检查失败:', error)
        // 继续执行请求，因为HEAD请求可能被阻止但POST仍然可用
      }
    },
    
    // 取消当前请求
    cancelRequest() {
      if (this.controller) {
        this.controller.abort()
        this.controller = null
        this.isStreaming = false
        this.connectionStatus = 'connected'
        this.$message.info('请求已取消')
      }
    },
    
    // 重新连接
    reconnect() {
      this.connectionStatus = 'connected'
      this.errorMessage = ''
    }
  }
}
</script>

<style scoped>
.chat-container {
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

/* 聊天内容区域 */
.chat-content {
  height: 65vh;
  min-height: 400px;
  overflow-y: auto;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  background-color: white;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* 消息项样式 */
.message-item {
  display: flex;
  animation: fadeIn 0.3s ease-out;
}

.message-item.self {
  justify-content: flex-end;
}

/* 消息内容气泡 */
.message-content {
  max-width: 75%;
  padding: 0.75rem 1.25rem;
  border-radius: var(--border-radius);
  word-wrap: break-word;
  line-height: 1.5;
  font-size: 0.95rem;
  position: relative;
  transition: all 0.2s ease;
}

/* 用户消息 */
.message-item.self .message-content {
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  color: white;
  border-bottom-right-radius: 4px;
}

/* AI消息 */
.message-item:not(.self) .message-content {
  background: #f1f3f5;
  color: var(--dark-text);
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 输入区域 */
.chat-input-area {
  border-radius: var(--border-radius);
  padding: 1rem 1.5rem;
  box-shadow: var(--box-shadow);
  background-color: white;
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.input-box {
  flex: 1;
}

.input-box >>> .el-input__inner {
  border-radius: 8px;
  padding: 0.75rem 1rem;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
}

.input-box >>> .el-input__inner:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.2);
}

/* 按钮样式 */
.el-button {
  border-radius: 8px;
  padding: 0.75rem 1.5rem;
  transition: all 0.3s ease;
  font-weight: 500;
}

.el-button--primary {
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  border: none;
}

.el-button--danger {
  background: linear-gradient(135deg, var(--danger-color), #d81159);
  border: none;
}

.el-button:active {
  transform: scale(0.98);
}

/* 状态提示 */
.el-alert {
  border-radius: var(--border-radius);
}

/* 调试信息区域 */
.debug-info {
  margin-top: 1.5rem;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  overflow: hidden;
}

.debug-title {
  font-weight: 600;
  margin-bottom: 0.75rem;
  color: #6c757d;
  font-size: 0.875rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

pre {
  background-color: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
  overflow-x: auto;
  font-size: 0.8125rem;
  line-height: 1.5;
  color: #495057;
  border-left: 4px solid var(--primary-color);
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    gap: 1rem;
  }
  
  .chat-content {
    height: 60vh;
    min-height: 300px;
    padding: 1rem;
  }
  
  .message-content {
    max-width: 85%;
    font-size: 0.875rem;
  }
  
  .chat-input-area {
    padding: 0.75rem;
    flex-direction: column;
  }
  
  .el-button {
    width: 100%;
    padding: 0.75rem;
  }
}
</style>